package com.example.myapplication;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethod;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.textfield.TextInputLayout;

public class LoginActivity extends AppCompatActivity {
  ImageView loadImage;
  boolean isLoaded;
  boolean isOnRegister = false;
  LinearLayout loginLayout;
  LinearLayout registerLayout;
  Button loginButton;
  Button registerButton;
  Button backButton;

  Button registerLogButton;



  TextInputLayout accountLogLayout;
  TextInputLayout accountRegLayout;
  TextInputLayout passwordLogLayout;
  TextInputLayout passwordRegLayout;
  TextInputLayout userNameRegLayout;

  EditText accountLogText;
  EditText accountRegText;
  EditText passwordLogText;
  EditText passwordRegText;

  EditText userNameRegText;


  UserDataBaseHelper userDataBaseHelper;

  @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.log_in_layout);
    userDataBaseHelper = new UserDataBaseHelper(this);
    Init();
    //需要补充的
    //链接外部数据库时同步更新本地SQLite的数据

  }

  private void Init() {
    loadImage = findViewById(R.id.load_img);
    loginLayout=findViewById(R.id.login_layout);
    loginLayout.setVisibility(View.INVISIBLE);
    loginButton = findViewById(R.id.login_button);
    registerButton=findViewById(R.id.reg_button);

    accountLogLayout = findViewById(R.id.account_layout);
    accountRegLayout = findViewById(R.id.reg_account_layout);
    accountLogText = findViewById(R.id.account_input);
    accountRegText = findViewById(R.id.reg_account_input);


    passwordLogLayout = findViewById(R.id.password_layout);
    passwordRegLayout = findViewById(R.id.reg_password_layout);
    passwordLogText = findViewById(R.id.password_input);
    passwordRegText = findViewById(R.id.reg_password_input);

    userNameRegLayout = findViewById(R.id.reg_username_layout);
    userNameRegText = findViewById(R.id.reg_username_input);


    registerLayout = findViewById(R.id.register_panel);
    registerLayout.setVisibility(View.INVISIBLE);

    backButton = findViewById(R.id.back_login_button);
    registerLogButton = findViewById(R.id.register_log_button);
    loadImage.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {

        if (!isLoaded) {
          StartShowAnimation(v);
          isLoaded = true;
        } else {
          if (isOnRegister) {
            StartDownAnimation(v, registerLayout);

          } else {
            StartDownAnimation(v, loginLayout);
          }
          isOnRegister=false;
          isLoaded = false;
        }
        InputMethodManager inputMethodManager =
            (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //隐藏软键盘
        inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);

      }
    });
    //return true可以抵消事件
    loginLayout.setOnTouchListener(new View.OnTouchListener() {
      @Override public boolean onTouch(View v, MotionEvent event) {
        //获取输入法管理器
        InputMethodManager inputMethodManager =
            (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //隐藏软键盘
        inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
        return true;
      }
    });
    registerLayout.setOnTouchListener(new View.OnTouchListener() {
      @Override public boolean onTouch(View v, MotionEvent event) {
        InputMethodManager inputMethodManager =
            (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //隐藏软键盘
        inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);

        return true;
      }
    });

    registerButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {

        StartWipeOutAnimation(loginLayout);
        StartWipeInAnimation(registerLayout);
        isOnRegister=true;
      }
    });
    backButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        StartWipeOutAnimation(registerLayout);
        StartWipeInAnimation(loginLayout);
        isOnRegister=false;
      }
    });

    loginButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {


        String account = String.valueOf(accountLogText.getText());
        String password = String.valueOf(passwordLogText.getText());
        if (CheckInputText(account, accountLogLayout) && CheckInputText(password,
            passwordLogLayout) && CheckPassword(account, password)) {

          LogIn(account);
          Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
        } else {
          Toast.makeText(LoginActivity.this, "请根据提示修改信息", Toast.LENGTH_SHORT).show();
        }
      }
    });
    registerLogButton.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        String account = String.valueOf(accountRegText.getText());
        String password = String.valueOf(passwordRegText.getText());
        String username = String.valueOf(userNameRegText.getText());
        if (CheckInputText(account, accountRegLayout) && CheckInputText(password,
            passwordRegLayout) && CheckInputText(username, userNameRegLayout)) {
          UserEntity user = new UserEntity(username, account, password);
          RegisterUserInfo(user);
          Toast.makeText(LoginActivity.this, "注册成功，马上登录...", Toast.LENGTH_SHORT).show();
        } else {
          Toast.makeText(LoginActivity.this, "请根据提示修改信息", Toast.LENGTH_SHORT).show();
        }
      }

    });
  }

  private void StartDownAnimation(View v,LinearLayout linearLayout) {
    Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_down);
    linearLayout.startAnimation(animation);

    linearLayout.setVisibility(View.INVISIBLE);

  }

  private void StartShowAnimation(View view) {
    Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_up);
    loginLayout.setVisibility(View.VISIBLE);
    loginLayout.startAnimation(animation);



  }

  private void StartWipeInAnimation(LinearLayout linearLayout) {
    Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_right_to_left_in);
    linearLayout.setVisibility(View.VISIBLE);
    linearLayout.startAnimation(animation);


  }

  private void StartWipeOutAnimation(LinearLayout linearLayout) {
    Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_right_to_left_out);
    linearLayout.startAnimation(animation);

    linearLayout.setVisibility(View.INVISIBLE);

  }

  private void LogIn(String account) {
    Intent intent = new Intent(this, MainActivity.class);

    userDataBaseHelper.Open();
    String name = userDataBaseHelper.GetUserNameByAccount(account);
    intent.putExtra("userAccount", account);
    intent.putExtra("userName", name);
    startActivity(intent);
    userDataBaseHelper.Close();
    finish();

  }

  private void RegisterUserInfo(UserEntity user) {
    userDataBaseHelper.Open();

    int number = userDataBaseHelper.InsertSingleUser(user);
    if (number == 1) {

      LogIn(user.getUserAccount());
    } else if(number==0) {
      accountRegLayout.setError("该用户已存在");

      Toast.makeText(this, "该用户已存在", Toast.LENGTH_SHORT).show();
    }else {
      Toast.makeText(this, "服务器好像开了点小差...", Toast.LENGTH_SHORT).show();
    }
    userDataBaseHelper.Close();

  }
  private boolean CheckInputText(String str, TextInputLayout layout) {
    if (str.isEmpty()) {
      layout.setError("输入不能为空");
      return false;
    }
    layout.setError(null);
    return true;
  }

  private boolean CheckPassword(String account, String password) {
    userDataBaseHelper.Open();
    int number = userDataBaseHelper.CheckUserPassword(account, password);
    userDataBaseHelper.Close();
    if (number == 1) {
      return true;
    } else {
      if (number == 0) {
        accountLogLayout.setError("账号或密码错误");
        passwordLogLayout.setError("账号或密码错误");
      } else {
        accountLogLayout.setError("用户不存在");
        passwordLogLayout.setError("");
      }
    }
    return false;
  }
}
